from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime
from database import Base

class DictType(Base):
    """数据字典主表 - 存储字典类型"""
    __tablename__ = "dict_types"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, index=True, nullable=False, comment="字典名称")
    code = Column(String(50), unique=True, index=True, nullable=False, comment="字典编码")
    description = Column(String(255), comment="字典描述")
    sort_order = Column(Integer, default=0, comment="排序")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关系
    dict_items = relationship("DictItem", back_populates="dict_type", cascade="all, delete-orphan")

class DictItem(Base):
    """数据字典子表 - 存储字典项"""
    __tablename__ = "dict_items"
    
    id = Column(Integer, primary_key=True, index=True)
    dict_type_id = Column(Integer, ForeignKey('dict_types.id'), nullable=False, comment="字典类型ID")
    label = Column(String(100), nullable=False, comment="显示标签")
    value = Column(String(100), nullable=False, comment="值")
    description = Column(String(255), comment="描述")
    sort_order = Column(Integer, default=0, comment="排序")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关系
    dict_type = relationship("DictType", back_populates="dict_items")